<template>
	<view class="all-box containers" style="margin-bottom:200rpx;">
		<view v-if="netWorkType!='none'">
         <!-- <tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton> -->
			<view class="container tui-skeleton" style="border-top: 1rpx solid #DDDDDD;">
				<view class="wifi-img-view margin-bottom15">
					<image class="publicImg" src="https://xoimg.aiouning.com/static/img/wifi.png" mode="widthFix"></image>
				</view>
				<view class="padleft30 padright30">
					<view class="font16 font-bold padbottom5 text-center">
						手机和设备必须连接同一个网络才能进行绑定
					</view>
					<view class="font12 font-gray padleft50 padright50 text-center">如果手机与设备不在同一个网络下，将无法检测到设备，既无法绑定</view>

					<view class="margintop66 font-gray2 font14 font-gray2 padbottom30 font-bold">
						当前网络
					</view>
					<view class="font14 font-bold line padbottom10">{{data.SSID}}</view>

					<view class="font-gray2 padtop18 font14 font-gray2 padbottom30 font-bold">
						密码
					</view>

					<view class="padtop15">
						<input v-model="data.password"  placeholder="请输入密码" class="padleft10 padright10 padtop5 padbottom5 wifi-input" />
					</view>
				</view>
				<view  class="nextStep bg-body font16"   @tap="AirKissConfigure">下一步</view>


			</view>
		</view>

		<uni-popup ref="machtModal" id='statePopup' type="center" :custom="true">
			<view class="macth-modal-main bg-white pad-all15 padbottom30 text-left">
				<view class="flex-box">
					<view class="font14 font-bold margin-bottom15 text-left margin-bottom15">开始配网</view>
					<!-- <icon @tap="closeMachtModal" class="padright5" type="clear" size="18"/> -->
				</view>

				<view class="state-txt">
					<view  class="padbottom10"><image v-if="!connDev" src="https://xoimg.aiouning.com/static/devgif.gif" mode="widthFix"  class="gif"></image><icon v-if="connDev" class="padright5" type="success_no_circle" size="16"/>设备连接WIFI成功</view>
					<view  class="padbottom10"><image v-if="!sendDev" src="https://xoimg.aiouning.com/static/devgif.gif" mode="widthFix"  class="gif"></image><icon v-if="sendDev"  class="padright5"  type="success_no_circle" size="16"/>设备连接手机成功</view>
					<view    class="padbottom10"><image v-if="!devConnFar" src="https://xoimg.aiouning.com/static/devgif.gif"  mode="widthFix"  class="gif"></image><icon v-if="devConnFar" class="padright5"  type="success_no_circle" size="16"/>绑定产品成功</view>
					<view   class="padbottom10"><image v-if="!initStatu" src="https://xoimg.aiouning.com/static/devgif.gif" mode="widthFix" class="gif"></image><icon v-if="initStatu" class="padright5"  type="success_no_circle" size="16"/>初始化成功</view>
				</view>


			</view>
		</uni-popup>
		<!-- 登录弹窗 -->
		<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />
		<!-- 提示弹框 -->
		<tui-tips ref="toast"></tui-tips>
	</view>
</template>
<script>
	import Vue from 'vue'
	import store from '@/store/index.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	// 公共底部
	// import btabbar from '@/components/indexBottomTable/bottomtabbar.vue'
	var {AppDevSdk}  = require('qcloud-iotexplorer-appdev-sdk');
	var WifiConfConstants = require('qcloud-iotexplorer-appdev-plugin-wificonf-core').constants;
	var AirKissPlug = require('qcloud-iotexplorer-appdev-plugin-wificonf-airkiss').default;

	var {
	 // 错误的中文描述
	 WifiConfErrorMsg,
	 // 步骤code
	 WifiConfStepCode,
	 // 步骤code的中文描述
	 WifiConfStepDesp
	} = WifiConfConstants;
	// console.log(AppDevSdk)
	import {
		mapGetters
	} from 'vuex';
	export default {
		components: {
			// btabbar,
			uniPopup
		},
		computed: {
			//注册网络状态
			...mapGetters(['netWorkType', 'loginStatus'])
		},
		data() {
			return {
				// 骨架屏
				skeletonShow: true,
				checkState:false,
				token: '',
				data: {
					SSID:'',
					password:'',
					list: []
				},
				timerID: null, //定时器
				bindDeviceToken:'',
				OSS_HOST:'',
				sdk:'',
				machtModal:true,
				connDev:false,
				sendDev:false,
				devConnFar:false,
				initStatu:false,
				udp:''
			}
		},
		onLoad() {
			let _this = this
			if (!this.loginStatus) {
				_this.$refs.popupvLogin.open()
				// let callback = function(url) {
					
				// }
				// var data = {
				
				// }
				// _this.$refer.toUrl(callback,data,'close')
			}
		
			// var that = this;
			// this.OSS_HOST = this.$service.getImgHost()
			// console.log(this.OSS_HOST)
			// this.getWifi()
			// console.log(888888888888)
			//获取token
			//this.connDev = true

			// this.connDev = true







			 // console.log(SoftApPlug)


			// sdk.requestApi('AppGetFamilyDeviceList', { FamilyId: 'default' })
			// .then(data => {
			//   // 请求成功
			//   console.log(data);
			// })
			// .catch(err => {
			//   // 请求失败
			//   console.error(err);
			// });
		},
		onShow() {
			
			// this.searchEquip()
			
			// this.getWifiToken();
			// var that = this;
						// this.OSS_HOST = this.$service.getImgHost()
						// console.log(this.OSS_HOST)
						this.getWifi()
						// console.log(888888888888)
						//获取token

						// this.connDev = true
					// 	let _this = this
					// 	// this.getWifiToken()
					// 	// console.log(this.getWifiToken())
					// 	let sdkOptions = {
					// 		getAccessToken:this.getWifiToken,
					// 		appKey:'mMZLgVffuYKpleecL',
					// 		debug:true
					// 	}

					//     this.sdk =new AppDevSdk(sdkOptions);

					// 	 this.sdk.init()
					// 	  AirKissPlug.install(this.sdk);


					// 	 this.sdk.requestApi('AppCreateDeviceBindToken')
					// 	   .then(data => {
					// 	     _this.bindDeviceToken = data.Token;
					// 		 console.log('bindtoken:')
					// 		 console.log(this.bindDeviceToken)
					// 	   });

						 // console.log(SoftApPlug)


						// sdk.requestApi('AppGetFamilyDeviceList', { FamilyId: 'default' })
						// .then(data => {
						//   // 请求成功
						//   console.log(data);
						// })
						// .catch(err => {
						//   // 请求失败
						//   console.error(err);
						// });



		},
		onUnload() {
			clearInterval(this.timerID); //清除定时器
		},

		methods: {
			getWifi() {
				//console.log(77777777777777777)
				let _this=this;
				wx.startWifi({
					success(result) {
						// console.log(result)
						wx.getConnectedWifi({
							success: function(cv) {
								//console.log(88888888888888)
								console.log(cv.wifi)
								_this.data.SSID=cv.wifi.SSID;
								console.log('wifi:'+_this.data.SSID)
								//SSID
								//BSSID
								//signalStrength
								//secure
								//frequency
							}

						})
					},
					fail(err){
						console.log(err)
					}
				})


			},
			binglogin(){
				
				// let _this = this;
				// let url = '';
				
				// let path = '/packageHealthy/pages/bind_equip/bind_qrcode';
				// _this.$refer.setVilit(path);
				// let callback = function(url) {
				// 	_this.$refs.popupvLogin.open()
				// }
				// var data = {
				
				// }
				// _this.$refer.toUrl(callback,data)
				// return 
			},
			// 绑定设备
			bindEquip() {
				let _this = this

				this.$refer.setVilit('/packageBind/pages/bind_equip/bind')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {

				}
				this.$refer.toUrl(callback, data)

				return

			},
			// 轮询
			searchEquip() {
				// console.log(777777777777777777)sss
				let _this = this;
				
				let num = 0;
				clearInterval(this.timerID);
				this.timerID = setInterval(function(row) {
					
					if(_this.initStatu)
					{
						// console.log(num)
						
						
						clearInterval(_this.timerID);
						_this.udp.close()
						let options = {
							msg: '绑定成功',
							type:'green'
						  };
						 
						_this.$refs.toast.showTips(options);
						_this.$refs['machtModal'].close()
						_this.connDev=false
						_this.sendDev=false
						_this.devConnFar=false
						_this.initStatu=false
						//去智能硬件首页
						// _this.$refer.setVilit('/packageHealthy/pages/device/blood-pressure/index')
						// let callback = function(url) {
						// 	_this.$refs.popupvLogin.open()
						// }
						// var data = {

						// }
						// _this.$refer.toUrl(callback,data,'reLaunch')
						return
					}
					num++
					// console.log('------------------')
					// console.log(num)
					if (num >= 20) {
						_this.udp.close()
						_this.connDev=false
						_this.sendDev=false
						_this.devConnFar=false
						_this.initStatu=false
						clearInterval(_this.timerID); //请求超次数，清除定时器
						let options = {
							msg: '配网超时,请检查wifi帐号密码',
							type:'danger'
						  };
						_this.$refs.toast.showTips(options);
						_this.$refs['machtModal'].close()

					}

				}, 3000)
			},
			async getWifiToken() {
				let _this = this
				const resp = await new Promise((resolve, reject) => {
				   let opt = {
				   	url: '/wifi/getAccessToken',
				   	method: 'get',
				   	data: {


				   	},
				   	success: function(res) {
						// console.log(7777777777777777777777)
				   		// console.log(res)
				   		if (res.status == 1) {
				   			// console.log(res.data)
				   			 const { Token, ExpireAt } = res.data;
							 resolve(res.data);
				   			//_this.token = Token
				   			// console.log(99999999999999999999)
				   			// console.log(Token)
				   			// console.log(ExpireAt)
				   			//  return {Token, ExpireAt}

				   		} else {
				   			reject(res);
				   		}

				   	},

				   };
				   if (_this.loginStatus) {
					    _this.$service.GetApi(opt) //网络
				    }
				 });
				// console.log('getWIfiTOken')
				//console.log(resp.Token)
				return {
				  Token: resp.Token,
				  ExpireAt: resp.ExpireAt,
				};
			},
			bindDev(mac) {
				let _this = this
				//过滤符合规范的数据
				
				let opt = {
					url: '/wifi/bindTestDev',
				
					data: {
						mac:mac
					},
					success: function(res) {
						console.log(res)
						if (res.status == 1) {
							_this.devConnFar=true
							_this.initStatu=true
				
						} else {
							_this.connDev = false
							_this.sendDev =false
				
							_this.udp.close()
							clearInterval(_this.timerID);
							let options = {
								msg: res.message,
								type:'danger'
							  };
							_this.$refs.toast.showTips(options);
							_this.$refs['machtModal'].close()
				
						}
				
					}
				};
				
				_this.$service.GetApi(opt) //网络

			},
			closeMachtModal(){
				this.$refs['machtModal'].close()
			},
			/**
			   * ArrayBuffer转字符串
			   * @param {ArrayBuffer} e 需要转换的ArrayBuffer类型数值
			   * @param {function} t 转换成功后的回调
			   */
			  getUint8Value(e, t) {
			    for (var a = e, i = new DataView(a), n = "", s = 0; s < i.byteLength; s++) n += String.fromCharCode(i.getUint8(s));
			    t(n);
			  },
			/**
			* mac校验
			*/
			validateMac(mac) {
			    mac = mac.toUpperCase();
			    var expre = /[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}/;
			    var regexp = new RegExp(expre);
			    if (!regexp.test(mac)) {
			        return false;
			    }

				return true
			},
			formatDevData(txt){
				let startIndex=txt.indexOf('x')+1;
				   let newArry=txt.substring(startIndex,txt.length).split(',');

				   let str=newArry[0]
				   let result=[];
				   for(var i=0,len=str.length;i<len;i++){
				       result += str[i];
				       if(i % 2 == 1 && i<str.length-1) result += ':';
				   }

				   let list=[result,newArry[1]]
				   return list
			},

			/**
			* AirKiss一键配网 _this.token,
			*/
			async AirKissConfigure({
				
			
				
				wifiInfo = {
				  SSID:this.data.SSID,
				  password: this.data.password
				},
				familyId = 'default',
				roomId='0',
				reporter,
				onStepChange,
				onStatusChange
				}) {
				  let _this = this
				 
				if(_this.connDev==true||_this.sendDev==true||_this.devConnFar==true||_this.initStatu==true)
				{
					_this.connDev=false
					_this.sendDev=false
					_this.devConnFar=false
					_this.initStatu=false
					let options = {
						msg: '配网状态异常,请重新配网',
						type:'danger'
					  };
					_this.$refs.toast.showTips(options);

					return
				}
				 _this.searchEquip()
				 // _this.initStatu=true
				   const resp = await new Promise((resolve, reject) => {
					     let sdkOptions = {
					     	getAccessToken:_this.getWifiToken,
					     	appKey:'mMZLgVffuYKpleecL',
					     	debug:false
					     }

						 let sdk =new AppDevSdk(sdkOptions);
						 //console.log('ssssiiii9999')
						// console.log(sdk)
						 sdk.init()

						 AirKissPlug.install(sdk);

						  sdk.requestApi('AppCreateDeviceBindToken')
						    .then(data => {
								let token = ''
								//ssss console.log('bindtoken:')
						        token = data.Token;
								resolve({sdk,token})
						    });

				   })
				 //   console.log('ssssiiii')
					//console.log(resp)
				//   return
				   // let sdkOptions = {
				   // 	getAccessToken:_this.getWifiToken,
				   // 	appKey:'mMZLgVffuYKpleecL',
				   // 	debug:true
				   // }


					this.$refs['machtModal'].open()
					// return
					// console.log('AirKiss start')
					// console.log(token)
				const onProgress = (data) => {
					// console.log(data)
					// console.log(WifiConfStepCode.WIFI_CONF_SUCCESS)
				  // reporter.info(data.code, data.detail);
				  // connDev:false,
				  // sendDev:false,
				  // devConnFar:false,
				  // initStatu:false
				   switch (data.code) {
					case WifiConfStepCode.WIFI_CONF_START:
					  console.log('开始配网')
					   //console.log(data)


					  // Vue.set(this.connDev,true)
					   //	console.log(this.connDev)
					  //onStepChange(1);
					  break;
					case WifiConfStepCode.PROTOCOL_START:
					  console.log('配网协议开始')
					  // console.log(data)
					   this.connDev = true

					   //每5秒检测一次是否配网成功
					   //创建UDP
					   // console.log(11111111111)
					    _this.udp = wx.createUDPSocket()
					     const port = _this.udp.bind(12476)

					    console.log(port)
					     _this.udp.onMessage(function(message,remoteInfo){
							 // console.log(99999999999999)  s
					   	  console.log('message:'+JSON.stringify(message))
					   	  _this.getUint8Value(message.message,function(val){
					   		   //console.log("start")
							   let devData = _this.formatDevData(val)
							   if(!_this.validateMac(devData[0]))
							   {
								   // let options = {
								   // 	msg: '非法mac地址',
								   // 	type:'danger'
								   //   };
								   // _this.$refs.toast.showTips(options);
								   return
							   }

							   if(_this.initStatu==true)
							   {

								   //已初始完成
								   return
							   }
							   _this.sendDev =true

							   _this.bindDev(devData[0])

					   		  // console.log(devData[0])
					   	  })
					     })
						_this.udp.offClose(function(){
							let options = {
								msg: 'UDP关闭',
								type:'danger'
							  };
							_this.$refs.toast.showTips(options);
						})

					  break;
					case WifiConfStepCode.PROTOCOL_DETAIL:
					  console.log('配网协议详情日志')
					   console.log(data)

					  //onStepChange(1);
					  break;
					case WifiConfStepCode.PROTOCOL_SUCCESS:
					  console.log('PROTOCOL_SUCCESS')
					   console.log(data)
					   this.connDev = true
					  //onStepChange(1);
					  break;

				    case WifiConfStepCode.WIFI_CONF_SUCCESS:
					console.log(data)
					console.log('配网成功')
					

				   //   onStepChange(5);
				      break;


				  }
				};
				const onComplete = () => {
					console.log(8999)
				  // onStatusChange({  { productId, deviceName }
				  //   status: 'success',
				  //   productId,
				  //   deviceName,
				  // });
				};
				 const onError = async ({ code, detail }) => {
					 _this.udp.close()
					 _this.connDev=false
					 _this.sendDev=false
					 _this.devConnFar=false
					 _this.initStatu=false
					 clearInterval(_this.timerID); //请求超次数，清除定时器
					 // let options = {
					 // 	msg: '配网超时,请检查wifi帐号密码',
					 // 	type:'danger'
					 //   };
					 // _this.$refs.toast.showTips(options);
					 // _this.$refs['machtModal'].close()
				  // reporter.error(code, detail);
				   // onStatusChange({ status: 'error' });
				};
				//console.log('sdk:')
				//console.log(resp.token)
				 resp.sdk.plugins['wifiConfAirKiss'].start({
				  wifiConfToken: resp.token,
				  targetWifiInfo: wifiInfo,
				  autoRetry: false, // 自动处理故障流程
				  familyId,
				  roomId,
				  onProgress,
				  onComplete,
				  onError
				});


				}

				// const { collectModuleLog } =  require('qcloud-iotexplorer-appdev-plugin-wificonf-core').utils;
				// collectModuleLog({
				//  // 用于上报的对象
				//  reporter: console,
				//  sdk: sdk,
				// })


				// uni.showLoading({
				//     title: '绑定中,请稍等'
				// });
				//this.bindDev();

				//this.searchEquip();
				// let _this = this

				// this.$refer.setVilit('/packageBind/pages/bind_equip/reset_equip')
				// let callback = function(url) {
				// 	_this.$refs.popupvLogin.open()
				// }
				// var data = {

				// }
				// this.$refer.toUrl(callback, data)

				// return



		}
	}
</script>

<style lang="scss">
	@import "./bind_qrcode.scss";
</style>
